package com.pxt.demo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

public class PathMoveView extends View {

    PointF start = new PointF(500, 500);
    PointF end = new PointF(1000, 700);
    Paint paint = new Paint();


    public PathMoveView(Context context) {
        super(context);
        init();
    }

    public PathMoveView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PathMoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(10);
        paint.setTextSize(30);
    }


    private String a = "aaaaaaaaaaaaaaaaaa";
    private String b = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Path path1 = new Path();
        path1.moveTo(start.x, start.y);
        path1.lineTo(end.x, end.y);
        canvas.drawTextOnPath(a, path1, 0, 0, paint);

        float angle = angle(start, end);

        float[] points = new float[]{0, 0, dist(start, end), 0};
        float[] points1 = new float[]{0, 0, paint.measureText(a) - paint.measureText(b), 0};
        Matrix matrix1 = new Matrix();
        matrix1.postRotate(angle);
        matrix1.postTranslate(start.x, start.y);
        matrix1.mapPoints(points1);

        Matrix matrix = new Matrix();
        matrix.postTranslate(0, -100);
        Log.e("PATH", "angle = " + angle);
        matrix.postRotate(angle);
        matrix.postTranslate(points1[2], points1[3]);
        matrix.mapPoints(points);
        Path path2 = new Path();
        path2.moveTo(points[0], points[1]);
        path2.lineTo(points[2], points[3]);
        canvas.drawTextOnPath(b, path2, 0, 0, paint);
    }


    // 两指间距离
    private float dist(PointF start, PointF end) {
        float x = start.x - end.x;
        float y = start.y - end.y;
        return (float) Math.sqrt(x * x + y * y);
    }


    // 取旋转角度
    private float angle(PointF start, PointF end) {
        double delta_x = (end.x - start.x);
        double delta_y = (end.y - start.y);
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }
}
